用Chart.js 套件畫一個長條圖,以及分行符號的應用
HTML:
<div class="card">
<header>Header Section</header>
<div class="main">
<canvas id="barChart"></canvas>
</div>
</div>
CSS:
*{
margin: 0; padding:0; box-sizing: border-box;
}
body {
font-family: sans-serif;
color: #333;
padding: 20px;
background: #f8f8f8;
}
.card {
max-width: 80%;
width: 100%;
margin: 0 auto;
box-shadow: 0px 22px 22px -20px rgba(0,0,0,0.3);
header {
height: 50px;
background: #ccc;
border-radius: 8px 8px 0 0;
display: flex;
align-items: center;
padding: 20px;
}
.main {
padding: 20px;
background: #fff;
border-radius: 0 0 8px 8px;
}
}
all.js:
//引入官網上的https://cdn.jsdelivr.net/npm/chart.js(不要用codepen尋找,會報錯Chart is undefined.)
//一開始先渲染canvas環境
const canvas = document.getElementById("barChart");
const ctx = canvas.getContext("2d");
Chart.defaults.color = "#2097e1";
//圖表字體預設顏色改為#2097e1
//getting started內的基本圖表樣式,先複製起來 new代表創建一個物件(圖表)
new Chart(ctx, {
type: "bar", //圖表類型
data: {
labels: [
"Sun\n09/24",
"Mon\n09/25",
"Thu\n09/26",
"Wed\n09/27",
"Thu\n09/28",
"Fri\n09/29"
],
datasets: [
//在datasets新增物件,可以增加Bar的組數
{
label: "雙十節快到了!", //長條圖數據1
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: "中秋節到了!", //長條圖數據2
data: [10, 9, 7, 5, 6, 3],
borderWidth: 1
}
]
},
options: {
//下面會把options單獨拉出來
scales: {
y: {
beginAtZero: true //y軸從0開始
}
}
}
});
const labelWrap = new Chart(ctx, {
plugins: [
{
beforeInit: function (chart) {
chart.data.labels.forEach(function (item, index, array) {
if (/\n/.test(item)) {
a[i] = item.split(/\n/);
}
});
}
}
]
});
補充:
Chart.js 套件介紹:
(一) Chart.js 套件相容性
Chart.js 內建的 TypeScript 型別,並且與所有JavaScript 框架兼容,包括 React、Vue、Svelte 和 Angular。
(二)Chart.js 圖表需渲染在canvas上
Chart.js 圖表是渲染在由canvas上的,在html中創建canvas畫布,才能使用Chart.js
(三)Chart.js 可匯出表格種類:
(四)Chart.js表格樣式
Chart.defaults.backgroundColor = '#9BD0F5'; //將圖表背景預設顏色改為#9BD0F5
Chart.defaults.borderColor = '#36A2EB'; //將圖表邊框預設顏色改為#36A2EB
Chart.defaults.color = '#000'; //將圖表字體預設顏色改為#000
BarChart連結:https://codepen.io/Ingridchen/pen/NWeyJyW
Reference
https://developer.mozilla.org/zh-TW/docs/Web/HTML/Element/canvas
https://www.chartjs.org/docs/latest/samples/bar/border-radius.html
https://codepen.io/abir_maiti/pen/rNxYdLq
https://www.youtube.com/watch?v=XInZCqIAygA&list=PLliocbKHJNwv7Vl3lnBwK52K5l84n7KNy&index=5